﻿<?php
mysql_connect("localhost","studysag_ecs","Mwansemo70");
mysql_select_db("studysag_ecs");
?>
<script type="text/javascript" language="javascript">
var richTextIsChange = false;
var timeTooltipInvisible = 2000;
var timerTooltipID;
var tooltipIsVisible = false;

$(function () {
    breaking();

    $("#richTextBox").mouseenter(function () {
        if (richTextIsChange) {
            breaking();
        }
    }).keyup(function () {
        richTextIsChange = true;
    }).blur(function () {
        if (richTextIsChange) {
            breaking();
        }
    });
    //bound event tooltip
    $("#tooltip").mouseover(function () {
        clearTimeout(timerTooltipID);
    }).mouseleave(function () {
        timerTooltipID = setTimeout("closeTooltip();", timeTooltipInvisible);
    });

    $(".toolbar-close").click(function () { closeTooltip(); })

})
function breaking() {
    var richTextBox = document.getElementById("richTextBox");
    var nodes = getTextNodesIn(richTextBox);
    for (var i = 0; i < nodes.length; i++) {
        var text = $(nodes[i]).text();
        if (text != "") {
            if (nodes[i].parentNode.tagName == "SPAN") {
                $(nodes[i].parentNode).replaceWith(breakingWords(text));
            }
            else {
                text = text.replace(/^\n*\s*/, "");
                if (text != "") {
                    $(nodes[i]).replaceWith(breakingWords(text));
                }
            }
        }
    }

    $(".tooltip-word").mouseover(function () {
        var isFound = loadDefinitionOfTerm(this);
        if (isFound) {
            showTooltip(this);
            clearTimeout(timerTooltipID);
            timerTooltipID = setTimeout("closeTooltip();", timeTooltipInvisible);
            tooltipIsVisible = true;
        }
    });
    richTextIsChange = false;
}

///load definition of term
///return true if the definition has found. otherwise false
function loadDefinitionOfTerm(term) {
    var text = $(term).text().toLowerCase();
    //remove redundacy characters at the begin
    text = text.replace(/^\.|,|\?|>|<|"|'|;|:|\(/, "");
    //remove redundacy characters at the end
    text = text.replace(/\.|,|\?|>|<|"|'|;|:|\)$/, "");
    //searching in you DB by using ajax and get json response 
    //in this case i use db in client machine. i store it at the end of the file

    var isFound = false;
    //loop
    for (var i = 0; i < arrDefinitionOfTerms.length; i++) {
        var def = arrDefinitionOfTerms[i];
        if (def.term == text) {            
            $("#tooltipHeader").text(text);
            $("#tooltipDefinition").text(def.definition);
            $("#tooltipLink").attr('href', def.url).text(def.url);
            isFound = true;
            break;
        }
    }
    return isFound;
}

function showTooltip(term) {
    var offset = $(term).offset();
    var tooltip = $("#tooltip");
    var windowWidth = getWindowWidth();
    var windowHeight = getWindowHeight();
    var tooltipWidth = tooltip.width();
    var tooltipHeight = tooltip.height();
    var x, y;
    //check width screen is still available for display
    var margin = 20;
    if (offset.left + tooltipWidth < windowWidth) {
        x = offset.left;
    }
    else {
        x = offset.left - tooltipWidth;
    }

    if (offset.top + tooltipHeight + margin < windowHeight) {
        y = offset.top + margin;
    }
    else {
        y = offset.top - tooltipHeight - margin;
    }

    tooltip.css({ left: x + "px", top: y + "px" }).fadeIn();
}

function breakingWords(text) {
    if (text.length == 1) {
        return "<span>" + text + "</span>";
    }
    else {
        text = text.replace(/&nbsp;/, " ");
        var result = "";
        var isReadText = text[0] != " " && text[0].charCodeAt(0) != 160;
        var i = 1;
        var start = 0;

        while (i < text.length) {
            if (isReadText) {
                while (i < text.length && text[i] != ' ' && text[i].charCodeAt(0) != 160) {
                    i++;
                }
                isReadText = false;
            }
            else {
                while (i < text.length && (text[i] == ' ' || text[i].charCodeAt(0) == 160)) {
                    i++;
                }

                isReadText = true;
            }
            var temp = text.substring(start, i);
            if (!isReadText) {
                result += "<span class='tooltip-word'>" + temp + "</span>";
            }
            else {
                result += "<span>" + temp + "</span>";
            }
            start = i;
            i++;
        }
    }

    return result;
}

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [];

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            textNodes.push(node);
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

function getWindowWidth() {
    var width = 0;
    if (window.innerWidth) {
        width = window.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth) {
        width = document.documentElement.clientWidth;
    }
    else if (document.body) {
        width = document.body.clientWidth;
    }
    return width;
}

function getWindowHeight() {
    var theHeight = 0;
    if (window.innerHeight) {
        theHeight = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        theHeight = document.documentElement.clientHeight;
    }
    else if (document.body) {
        theHeight = document.body.clientHeight;
    }
    return theHeight;
}

function closeTooltip() {
    tooltipIsVisible = false;
    $('#tooltip').fadeOut();
    clearTimeout(timerTooltipID);
}

/*************************************************** TEST DATA **********************************************/
//this is an array of terms that has definition.
var arrTerms = [  
				<?php
				$all = mysql_query("select * from tooltip");
				$tots = mysql_num_rows(mysql_query("select * from tooltip"));
				$i = 1;
				while($tooltip = mysql_fetch_array($all))
				{
					$comma = ($tots>$i)? ", " : "";
					echo "'".$tooltip['terms']."' ".$comma;
					$i++;
				}
				?>
				];

//for example this is data in your DB
var arrDefinitionOfTerms = [
    <?php
	$all = mysql_query("select * from tooltip");
	$tots = mysql_num_rows(mysql_query("select * from tooltip"));
	$i = 1;
	while($tooltip = mysql_fetch_array($all))
	{
		$comma = ($tots>$i)? ", " : "";
	?>
	{ term: '<?php echo $tooltip['terms'];?>', definition: 'Definition:" <?php echo $tooltip['definition'];?>"', url: '<?php echo $tooltip['url'];?>' }<?php echo $comma;?>
	<?php $i++;}?>
   ];
/*************************************************** TEST DATA **********************************************/
</script>